package com.jiangyg.mall.core.support.validation.constraints;

import com.jiangyg.mall.core.support.validation.AbstractConstraintValidator;
import com.jiangyg.mall.core.utils.Logger;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * 枚举描述：校验参数是否满足枚举类型
 *
 * @author jiangyg
 * @version 4.0
 * @date 2022-12-14
 */
@Documented
@Retention(RUNTIME)
@Constraint(validatedBy = {Enum.EnumConstraintValidator.class})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
public @interface Enum {

    /**
     * 指定枚举的类
     */
    Class<?> value();

    /**
     * 指定参数值与枚举那个字段比较，默认：code
     */
    String field() default "code";

    String message() default "{custom.validation.constraints.enum.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * 类描述：验证int数值执行器
     *
     * @author jiangyg
     * @version 2.0
     * @date 2021-09-30
     */
    @Slf4j
    class EnumConstraintValidator extends AbstractConstraintValidator<Enum, Object> {

        @Override
        public boolean execute(Enum anEnum, Object value, ConstraintValidatorContextImpl contextImpl) {
            try {
                final Class<?> clazz = anEnum.value();
                // 获取枚举的常量值
                final Object[] constants = clazz.getEnumConstants();
                // 获取枚举值的字段
                final Field field = clazz.getDeclaredField(anEnum.field());
                // 校验是否有满足的枚举类型（只要有一项满足就校验通过）
                boolean success = false;
                for (Object constant : constants) {
                    final Object val = field.get(constant);
                    if (val instanceof Number && val == value) {
                        success = true;
                        break;
                    }
                    if (val instanceof String && val.equals(value)) {
                        success = true;
                        break;
                    }
                    // TODO 待补充其他类型
                }
                return success;
            } catch (Exception ex) {
                Logger.error(log, () -> "[参数校验]-枚举类型参数校验出错", ex);
                return false;
            }
        }

    }

}
